package com.qf.shop.order.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

@Component
@Slf4j
public class FeignHeadInterceptor implements RequestInterceptor {

    /**
     * @param requestTemplate feign调用时新创建的请求对象
     */
    @Override
    public void apply(RequestTemplate requestTemplate) {
        requestTemplate.header("name", "value");

        // 1.获取HttpServletRequest对象 ,从天ThreadLocal中获取的
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        log.debug("requestAttributes:{}",requestAttributes);
        log.debug("url:{}",requestTemplate.request().url());

        if(requestAttributes != null){
            HttpServletRequest request = requestAttributes.getRequest();

            // 2.从req对象中获取请你头
            Enumeration<String> headerNames = request.getHeaderNames();

            // 3.遍历
            while (headerNames.hasMoreElements()) {
                String key = headerNames.nextElement();
                String value = request.getHeader(key);

                // 复制了上一个请求头的content-length，requestBody数据不一致
                if (key.equals("content-length")){
                    continue;
                }
                // 3.全部放到新的请求头中
                requestTemplate.header(key, value);
            }
        }
    }
}
